package stack.be.touch.adapter;

import java.util.ArrayList;
import java.util.Collections;

import stack.be.touch.dto.SiteDTO;
import stack.be.touch.ui.PickSitesActivity;

import stack.be.touch.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;

public class SitesPickerAdapter extends ArrayAdapter<SiteDTO> {	
	private ArrayList<SiteDTO> sites;
	private Activity context;
	private ListView lv;
	
	private boolean isCodeCheck = false;

	public SitesPickerAdapter(Activity context, int textViewResourceId,
			ArrayList<SiteDTO> sites) {
		super(context, textViewResourceId, sites);
		this.context = context;
//		this.sites = PickSitesActivity.mSites;	
		this.sites = sites;
	}
	
	private static class ViewHolder {
		protected TextView tv;
		protected CheckBox chk;
		protected Button btnUp;
		protected Button btnDown;
	}

	@Override
	public int getCount() {
		return sites.size();
	}
	
	@Override
	public SiteDTO getItem(int position) {
		return sites.get(position);
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewHolder holder;

		if (convertView == null) {
			convertView = context.getLayoutInflater().inflate(R.layout.row_checked, null);
			holder = new ViewHolder();
			holder.tv = (TextView)convertView.findViewById(R.id.listName);
			holder.chk = (CheckBox)convertView.findViewById(R.id.check);
			holder.chk.setOnCheckedChangeListener(onCheckListener);
			convertView.setTag(holder);			
		}else{
			holder = (ViewHolder)convertView.getTag();			
		}		
		
		holder.tv.setText(sites.get(position).getName());		
		this.isCodeCheck = true;
		holder.chk.setChecked(sites.get(position).isChecked()>0?true:false);
		this.isCodeCheck = false;
		holder.chk.setTag(position);
		
		return convertView;	
	}
	
	CompoundButton.OnCheckedChangeListener onCheckListener = new CompoundButton.OnCheckedChangeListener() {
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			if(isCodeCheck) {
				return;
			}
		
			int position = (Integer)buttonView.getTag();			
			SiteDTO site = sites.get(position);
			site.setChecked(isChecked ? 1 : 0);			
			if(isChecked) {
				sites.remove(position);
				sites.add(0, site);
				notifyDataSetChanged();
			}
		}
	};
	
}
